package com.example.haxballandroid;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;

import phone.beans.GameServerBean;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.DragEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.DragShadowBuilder;
import android.view.View.OnDragListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class TeamActivity extends Activity {
	
	private ListView teamA, teamB, spectator;
	private TextView name, score, time;
	private ArrayList<String> aPlayers, bPlayers, sPlayers;
	private ArrayAdapter<String> aAdapter, bAdapter, sAdapter;
	private Intent intent;
	public final static String TEAM_CHANGE = "com.example.haxballandroid.MESSAGE";
	public static GameServerBean updateBean;
	private boolean leftClick = false;
	private boolean rightClick = false;
	private boolean itemClick = false;
	public final static String TEAMCHANGE = "com.example.haxballandroid.MESSAGE";
	
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_team);
		
		intent = new Intent(this, ActionUpdate.class);
		teamA = (ListView)findViewById(R.id.team_1);
		teamA.setOnItemClickListener(listener);
//		teamA.setOnDragListener(new ChoiceDragListener()); //Setting up the listview for dragging and dropping
		
		teamB = (ListView)findViewById(R.id.team_2);
		teamB.setOnItemClickListener(listener);
//		teamB.setOnDragListener(new ChoiceDragListener());
		
		spectator = (ListView)findViewById(R.id.spec);
		spectator.setOnItemClickListener(listener);
//		spectator.setOnDragListener(new ChoiceDragListener());
		
		name = (TextView)findViewById(R.id.team_game_name);
		score = (TextView)findViewById(R.id.team_score);
		time = (TextView)findViewById(R.id.team_time);
		
		updateUI();
		
	}
	
	public BroadcastReceiver broadcastReceiver = new BroadcastReceiver(){
		
		@Override
		public void onReceive(Context arg0, Intent arg1) {
			// TODO Auto-generated method stub
			
			updateUI();
		}

	};
	
	public void updateUI(){
		updateBean = ActionUpdate.updateBean;
		if(updateBean !=null){
			aPlayers = new ArrayList<String>();
			bPlayers = new ArrayList<String>();
			sPlayers = new ArrayList<String>();
			int team;
			
			Log.d("PlayerList", ""+updateBean.getNumPlayers());
			for(String name : updateBean.getGameModel().getPlayerList().keySet()){
				team = updateBean.getGameModel().getPlayerList().get(name).getTeam();
				if(team==0){
					aPlayers.add(name);
				}
				if(team==1){
					bPlayers.add(name);
				}
				if(team==2){
					sPlayers.add(name);
				}
			}
			
			aAdapter = new ArrayAdapter<String>(this, R.layout.rowtextview, aPlayers);
			teamA.setAdapter(aAdapter);
			bAdapter = new ArrayAdapter<String>(this, R.layout.rowtextview, bPlayers);
			teamB.setAdapter(bAdapter);
			sAdapter = new ArrayAdapter<String>(this, R.layout.rowtextview, sPlayers);
			spectator.setAdapter(sAdapter);
			
			name.setText(updateBean.getName());
			score.setText(""+updateBean.getGameModel().getScoreboard().getMaxScore());
			time.setText(""+updateBean.getGameModel().getScoreboard().getTimeLeft().getMinute()+":"+updateBean.getGameModel().getScoreboard().getTimeLeft().getSecond());
			
		}
		else{
			//Testing Purposes
//			String[] pA = new String[] {"serv1", "serv2", "serv3", "serv4", "serv5","serv6", "serv7", "serv8", "serv9", "serv10", "serv11", "serv12"};
			
		}
		
	
		
	}
	
	//Receives the left button click
	public void movePlayerLeft(View view){
		if(itemClick){
			leftClick = true;
		}
		Log.d("Left", "Click");
	}
	
	//Receives the right button click
	public void movePlayerRight(View view){
		if(itemClick){
			rightClick = true;
		}
		Log.d("Right", "Click");
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_team, menu);
		return true;
	}
	
	
	public void startGame(View view){
		Intent intentAct = new Intent(this, GameFieldActivity.class);
		Intent intentServ = new Intent(this, ActionUpdate.class);
		startService(intentServ);
		startActivity(intentAct);
	}
	
	OnItemClickListener listener = new OnItemClickListener(){

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			sendTeamChange(arg0, arg1, arg2);
			Log.d("Item", "Click");
			itemClick = true;
		}
		
	};
	
	//Update the teams list after change of teams
	public void sendTeamChange(AdapterView<?> parent, View view, int position){
		if(parent.getAdapter() == aAdapter){
			if(rightClick){
				this.sendTeamChange(aAdapter.getItem(position), 2);
				sAdapter.add(aAdapter.getItem(position));
				aAdapter.remove(aAdapter.getItem(position));
				
				rightClick = false;
				
			}
		}
		if(parent.getAdapter() == sAdapter){
			if(leftClick){
				this.sendTeamChange(sAdapter.getItem(position), 1);
				aAdapter.add(sAdapter.getItem(position));
				sAdapter.remove(sAdapter.getItem(position));
				leftClick = false;
				
				
			}
			if(rightClick){
				this.sendTeamChange(sAdapter.getItem(position), 3);
				bAdapter.add(sAdapter.getItem(position));
				sAdapter.remove(sAdapter.getItem(position));
				rightClick = false;
			}
			
		}
		if(parent.getAdapter() == bAdapter){
			if(leftClick){
				this.sendTeamChange(bAdapter.getItem(position), 2);
				sAdapter.add(bAdapter.getItem(position));
				bAdapter.remove(bAdapter.getItem(position));
				leftClick = false;
				
			}
		}
	}
	
	public void sendTeamChange(String player, int team){
		Log.d("Team", "Update");
		intent = new Intent(this, ActionUpdate.class);
		intent.putExtra(TEAMCHANGE, "teamChange");
		intent.putExtra("Player", player);
		intent.putExtra("TeamChange", team);
		startService(intent);
	}
	
	/**
	  OnItemLongClickListener listSourceItemLongClickListener
	  = new OnItemLongClickListener(){

	  
		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			// TODO Auto-generated method stub
			//Selected item is passed as item in dragData
			   ClipData.Item item = new ClipData.Item(month[position]);
			   
			   String[] clipDescription = {ClipDescription.MIMETYPE_TEXT_PLAIN};
			   ClipData dragData = new ClipData((CharSequence)v.getTag(),
			     clipDescription,
			     item);
			   DragShadowBuilder myShadow = new MyDragShadowBuilder(v);
	
			   v.startDrag(dragData, //ClipData
			                  myShadow,  //View.DragShadowBuilder
			                  month[position],  //Object myLocalState
			                  0);    //flags
			   
			   commentMsg = v.getTag() + " : onLongClick.\n";
			   comments.setText(commentMsg);
			   
			   return true;
		}};
	*/
	
	/**
	 * Drag Shadow Builder builds a shadow when a drag is being done
	 * @author VARUN
	 *
	 */
	private static class MyDragShadowBuilder extends View.DragShadowBuilder {

	    // The drag shadow image, defined as a drawable thing
	    private static Drawable shadow;

	        // Defines the constructor for myDragShadowBuilder
	        public MyDragShadowBuilder(View v) {

	            // Stores the View parameter passed to myDragShadowBuilder.
	            super(v);

	            // Creates a draggable image that will fill the Canvas provided by the system.
	            shadow = new ColorDrawable(Color.LTGRAY);
	        }
	        

	        // Defines a callback that sends the drag shadow dimensions and touch point back to the
	        // system.
	        @Override
	        public void onProvideShadowMetrics (Point size, Point touch){
	            // Defines local variables
	            int width;
	            int height;

	            // Sets the width of the shadow to half the width of the original View
	            width = getView().getWidth() / 2;

	            // Sets the height of the shadow to half the height of the original View
	            height = getView().getHeight() / 2;

	            // The drag shadow is a ColorDrawable. This sets its dimensions to be the same as the
	            // Canvas that the system will provide. As a result, the drag shadow will fill the
	            // Canvas.
	            shadow.setBounds(0, 0, width, height);

	            // Sets the size parameter's width and height values. These get back to the system
	            // through the size parameter.
	            size.set(width, height);

	            // Sets the touch point's position to be in the middle of the drag shadow
	            touch.set(width / 2, height / 2);
	        }

	        // Defines a callback that draws the drag shadow in a Canvas that the system constructs
	        // from the dimensions passed in onProvideShadowMetrics().
	        @Override
	        public void onDrawShadow(Canvas canvas) {

	            // Draws the ColorDrawable in the Canvas passed in from the system.
	            shadow.draw(canvas);
	        }
	    }
	
	
	/**
	 * The drag listener which listens to the player being dropped into the team
	 * @author VARUN
	 *
	 */
	private class ChoiceDragListener implements OnDragListener {

		@Override
		public boolean onDrag(View arg0, DragEvent event) {
			// TODO Auto-generated method stub
			switch (event.getAction()) {
		    case DragEvent.ACTION_DRAG_STARTED:
		        //no action necessary
		        break;
		    case DragEvent.ACTION_DRAG_ENTERED:
		        //no action necessary
		        break;
		    case DragEvent.ACTION_DRAG_EXITED:
		        //no action necessary
		        break;
		    case DragEvent.ACTION_DROP:
		        //handle the dragged view being dropped over a drop view
		        break;
		    case DragEvent.ACTION_DRAG_ENDED:
		        //no action necessary
		        break;
		    default:
		        break;
			}
			return true;
		}
		
	}

}
